
package Chatter::API::Controller::timelines;

use Moose;
use Data::Dumper;
BEGIN { extends 'Catalyst::Controller'; }

# タイムライン一覧照会
sub root :Path('') {
  my ($self, $c) = @_;

  my $timelines = $c->stash->{tTweet}->search(
    undef, { order_by => { -desc => 'posted' }, rows => 200 }
  );

  my @jsons;
  while(my $timeline = $timelines->next){
    my $json;
    $json->{threadRoot} = $timeline->type eq "thread" ? "true" : "false" ;
    $json->{name}       = $timeline->account->name;
    $json->{accountId}  = $timeline->accountId;
    $json->{threadId}   = $timeline->threadId;
    $json->{groupId}    = $timeline->groupId;
    $json->{posted}     = $timeline->posted;
    $json->{tweet}      = $timeline->tweet;
    push(@jsons,$json);
  }
  $c->stash->{timelines} = \@jsons;
  $c->forward('View::JSON');
}

# 個人タイムライン照会
sub default :LocalRegex('^(.*)$') {
  my ($self, $c) = @_;
  my $id = $c->req->captures->[0];

  # メールアドレスからアカウントID取得
  my $user = $c->stash->{tAccount}->single(
    { email => $id }
  );

  # 存在しなければ終了
  unless($user){
    $c->stash->{timelines} = undef;
    $c->forward('View::JSON');
    $c->detach();
  }

  # スレッド検索
  my $timelines = $c->stash->{tTweet}->search(
    { accountId => $user->accountId },
    { order_by => { -desc => 'posted' }, rows => 200 }
  );

  my @jsons;
  while(my $timeline = $timelines->next){
    my $json;
    $json->{threadRoot} = $timeline->type eq "thread" ? "true" : "false" ;
    $json->{name}       = $timeline->account->name;
    $json->{accountId}  = $timeline->accountId;
    $json->{threadId}   = $timeline->threadId;
    $json->{groupId}    = $timeline->groupId;
    $json->{posted}     = $timeline->posted;
    $json->{tweet}      = $timeline->tweet;
    push(@jsons,$json);
  }
  $c->stash->{timelines} = \@jsons;
  $c->forward('View::JSON');
}

__PACKAGE__->meta->make_immutable;
1;

